package com.tang.service.adapter;

import com.tang.service.AdvancedMediaPlayer;
import com.tang.service.MediaPlayer;
import com.tang.service.utils.MediaUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 播放适配器
 *
 * @author fulin.tang
 * @version V3.0
 * @since 2021/9/16 14:10
 */
@Slf4j
public class MediaAdapter implements MediaPlayer {

    private final String audioType;

    AdvancedMediaPlayer advancedMusicPlayer;

    public MediaAdapter(String audioType) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        this.audioType = audioType;
        String clazz = MediaUtil.getInstance().mediaMap.get(audioType);
        Class<AdvancedMediaPlayer> advancedMediaPlayerClass = (Class<AdvancedMediaPlayer>) Class.forName(clazz);
        advancedMusicPlayer = advancedMediaPlayerClass.newInstance();
        log.info("反射新建了AdvanceMediaPlayer！audioType： {}", audioType);
    }

    @Override
    public void play(String audioType, String fileName) {
        String clazz = MediaUtil.getInstance().mediaMap.get(audioType);
        String advancedMusicPlayerClass = advancedMusicPlayer.getClass().getName();
        if (!Objects.equals(clazz, advancedMusicPlayerClass)) {
            log.info("不支持格式");
            return;
        }
        advancedMusicPlayer.play(fileName);
    }

    public String getAudioType() {
        return audioType;
    }

}
